package com.ktwlrj.core.util;

import com.alibaba.fastjson.JSONObject;
import com.ktwlrj.core.base.DetailEntity;
import com.ktwlrj.core.config.properties.AppProperty;
import com.ktwlrj.core.constant.Constant;
import com.ktwlrj.core.constant.ResultCode;
import com.ktwlrj.core.exception.ActionException;
import com.ktwlrj.core.feign.McClient;
import com.ktwlrj.core.util.convert.ConvertUtil;
import com.ktwlsoft.framework.user.cache.mvc.CurrentContextFeoPlat;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author zhouxuanhong
 * @date 2019-05-22 07:00
 * @since JDK1.8
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ContextHolderUtils {
    private final AppProperty appProperty;
    private final McClient mcClient;

    /**
     * 获取当前会员id
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:13
     */
    public String getUserId() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getMemberId() : null;
    }


    /**
     * 获取当前会员登录选择机构的名称
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:13
     */
    public String getCurrentOrgName() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getCurrentOrgName() : null;
    }


    /**
     * 获取当前用户开放id
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:14
     */
    public String getOpenId() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getOpenId() : null;
    }


    /**
     * 获取当前用户账号
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:14
     */
    public String getAccount() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getAccount() : null;
    }


    /**
     * 获取当前用户手机号
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:14
     */
    public String getMobilePhone() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getMobilePhone() : null;
    }


    /**
     * 获取当前用户真实姓名
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-25 11:14
     */
    public String getRealName() {
        DetailEntity detailEntity = getDetailEntity();
        return detailEntity != null ? detailEntity.getRealName() : null;
    }


    /**
     * 获取当前用户登录机构id
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-05-28 11:50
     */
    public String getCurrentOrgId() {
        String currentOrgId = "";
        DetailEntity detailEntity = getDetailEntity();
        if (detailEntity != null) {
            currentOrgId = detailEntity.getCurrentOrgId();
        }
        return currentOrgId;
    }


    /**
     * 从session获取用户详细信息
     *
     * @return DetailEntity ${@link DetailEntity}
     * @author zhouxuanhong
     * @date 2019-05-25 12:29
     */
    public DetailEntity getDetailEntity() {
        if (appProperty.isOpenAuth()) {
            com.ktwlsoft.framework.model.MemberInfoDto memberInfoDto = CurrentContextFeoPlat.getMemberUserByToken();
            log.debug("----------SystemServiceImpl---------->getUserByToken:{}", memberInfoDto);
            if (memberInfoDto == null) {
                throw new ActionException(ResultCode.AUTH_SESSION_TIMEOUT.getValue(), "授权过期,请刷新页面再次进入系统");
            }
            // 获取用户基本信息
            try {
                DetailEntity detailEntity = ConvertUtil.map(memberInfoDto, DetailEntity.class);
                return detailEntity;
            } catch (Exception e) {
                throw new ActionException(ResultCode.AUTH_SESSION_TIMEOUT.getValue(), "会员中心接口请求失败：" + e.getMessage());
            }
        } else {
            return new DetailEntity(true);
        }
    }


    /**
     * 获取当前用户机构权限信息
     *
     * @param busiCode ${@link String}
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-08-12 16:35
     */
    public List<String> getListOrgIds(String busiCode) throws RuntimeException {
        String orgIds = this.getCurrentOrgId();
        if (checkHavingAuthInfo(busiCode)) {
            JSONObject dataAuth = getDataAuth();
            if (dataAuth != null && !dataAuth.isEmpty()) {
                JSONObject jsonObject = dataAuth.getJSONObject(busiCode);
                if (jsonObject != null && !jsonObject.isEmpty()) {
                    orgIds += jsonObject.getString(Constant.ORG_IDS) == null ? "" : "," + jsonObject.getString(Constant.ORG_IDS);
                }
            }
        }
        String[] orgid = orgIds.split(",");
        return Arrays.asList(orgid);
    }


    /**
     * 获取当前用户权限信息(包含三个模块的:depositConf,depositManage,depositRegulatory,presellRegulatory)
     *
     * @return JSONObject ${@link JSONObject}
     * @throws RuntimeException ${@link RuntimeException}
     * @author zhouxuanhong
     * @date 2019-07-31 16:49
     */
    private static JSONObject getDataAuth() throws RuntimeException {
        HttpSession httpSession = getHttpSession();
        return Optional.ofNullable(httpSession).map(hs -> (JSONObject) hs.getAttribute(Constant.USER_DATA_AUTH))
                .orElse(null);
    }


    /**
     * 判断当前用户是否拥有权限信息
     *
     * @param busiCode ${@link String} 业务编码
     * @author zhouxuanhong
     * @date 2019-08-12 16:32
     */
    private static boolean checkHavingAuthInfo(String busiCode) {
        JSONObject auth = getDataAuth();
        if (auth != null && !auth.isEmpty()) {
            JSONObject jsonObject = auth.getJSONObject(busiCode);
            if (jsonObject != null && !jsonObject.isEmpty()) {
                String orgAuth = jsonObject.getString(Constant.ORG_IDS);
                return StringUtils.isNotBlank(orgAuth);
            }
        }
        return false;
    }


    private static HttpSession getHttpSession() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Optional.ofNullable(requestAttributes)
                .map(sr -> sr.getRequest())
                .map(re -> re.getSession())
                .orElse(null);
    }
}
